package com.zx._09_架构.rpc演变过程.rpc_04;

import com.zx._09_架构.rpc演变过程.service.impl.UserServiceImpl;
import com.zx.common.entity.UserRpcDto;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Server {

    public static void main(final String[] args) throws Exception {
        final ServerSocket ss = new ServerSocket(8888);
        Socket socket = null;
        while ((socket = ss.accept()) != null) {
            process(socket);
            socket.close();
        }
        ss.close();
    }

    public static void process(final Socket socket) throws Exception {
        final InputStream inputStream = socket.getInputStream();
        final OutputStream outputStream = socket.getOutputStream();

        final ObjectInputStream input = new ObjectInputStream(inputStream);
        final DataOutputStream output = new DataOutputStream(outputStream);

        // 获得请求中需要调用的方法信息
        final UserServiceImpl impl = new UserServiceImpl();
        final String methodName = input.readUTF();
        final Class<?>[] parameterTypes = (Class<?>[]) input.readObject();
        final Object[] args = (Object[]) input.readObject();

        final Method method = impl.getClass().getMethod(methodName, parameterTypes);

        final UserRpcDto userRpcDto = (UserRpcDto) method.invoke(impl, args);

        log.info("provider = {}", userRpcDto.toString());
        // 将结果写回去
        output.writeLong(userRpcDto.getId());
        output.writeUTF(userRpcDto.getName());

        output.flush();
    }
}
